<template>
    <div class="goods b">
        <div class="d">
            <lay-tab type="card" v-model="current">
                <lay-tab-item title="商品管理" id="1">
                    <div class="d">
                        <lay-table :columns="columns" :data-source="dataSource" even :page="page"
                            style="min-height: 300px;height: 550px;" :loading="goodsLoading"
                            @row-double="addData('编辑', $event)">
                            <template v-slot:toolbar>
                                <div class="flex">
                                    <div class="div">
                                        <lay-button size="sm" type="primary" @click="addData('添加', '')">
                                            新增商品</lay-button>
                                    </div>
                                    <div class="div">
                                        <lay-input size="sm" v-model="queryValue" placeholder="输入商品关键词" @append="">
                                            <template #suffix>
                                                <lay-icon type="layui-icon-search"
                                                    @click="QueryChangeGoods()"></lay-icon> &nbsp;
                                            </template>
                                        </lay-input>
                                    </div>
                                </div>
                            </template>
                            <template #image="{ row }">
                                <lay-tooltip trigger="hover" position="right">
                                    <lay-avatar :src="row.productImage" size="lg"></lay-avatar>
                                    <template #content>
                                        <lay-avatar :src="row.productImage" size="lg"
                                            style="width: 200px;height: 200px;"></lay-avatar>
                                    </template>
                                </lay-tooltip>
                            </template>
                            <template #goodsReturn="{ row }">
                                <p style="color: #d81e06;">
                                    {{ row.goodsReturn }}
                                </p>
                                <img src="../../assets/rise.png" style="width: 20px;" alt="">
                            </template>
                            <template #sts="{ row }">
                                <lay-tag type="primary" v-if="row.productSts == '已下架'">已下架</lay-tag>
                                <lay-tag type="normal" v-if="row.productSts == '已上架'"> 已上架</lay-tag>
                                <lay-tag type="danger" v-if="row.productSts == '待发售'">待发售</lay-tag>
                            </template>
                            <template #monthTurnover="{ row }">
                                <p style="color: #d81e06;">
                                    {{ row.monthTurnover }}
                                </p>
                                <img src="../../assets/rise.png" style="width: 20px;" alt="">
                            </template>
                            <template v-slot:operation="{ row }">
                                <lay-button type="primary" size="xs" @click="addData('编辑', row)">编辑</lay-button>
                                <lay-button type="danger" size="xs" @click="deleteData(row)">删除</lay-button>
                            </template>
                        </lay-table>
                    </div>
                </lay-tab-item>
                <!-- <lay-tab-item title="商品分类" id="2">
                    <div class="d">
                        <lay-button @click="addTab()" type="primary" size="sm">添加分类</lay-button>
                        <lay-tab type="brief" v-model="currentType">
                            <lay-tab-item v-for="(item, index) in typeTabList" :title="item.name" :id="item.id">
                                <lay-table :columns="columnsTab" :data-source="dataSource" even :page="pageTab"
                                    :loading="loadingTab" @row-double="addData('编辑', $event)">
                                    <template v-slot:toolbar>
                                        <div class="flex">
                                            <div class="div">
                                                <lay-button size="sm" type="primary" @click="addData('添加', '')">
                                                    新增商品</lay-button>
                                            </div>
                                            <div class="div">
                                                <lay-select v-model="goodsSts" placeholder="请选择" size="sm"
                                                    style="width: 120px;">
                                                    <lay-select-option :value="1" label="全部"></lay-select-option>
                                                    <lay-select-option :value="2" label="已上架"></lay-select-option>
                                                    <lay-select-option :value="3" label="已下架"></lay-select-option>
                                                    <lay-select-option :value="4" label="待发售"></lay-select-option>
                                                </lay-select>
                                            </div>
                                            <div class="div">
                                                <lay-input size="sm" suffix-icon="layui-icon-search"
                                                    placeholder="输入商品关键词">
                                                </lay-input>
                                            </div>
                                        </div>
                                    </template>
                                    <template #image="{ row }">
                                        <lay-tooltip trigger="hover" position="right">
                                            <lay-avatar :src="row.image" size="lg"></lay-avatar>
                                            <template #content>
                                                <lay-avatar :src="row.image" size="lg"
                                                    style="width: 200px;height: 200px;"></lay-avatar>
                                            </template>
                                        </lay-tooltip>
                                    </template>
                                    <template #goodsReturn="{ row }">
                                        <p style="color: #d81e06;">
                                            {{ row.goodsReturn }}
                                        </p>
                                        <img src="../../assets/rise.png" style="width: 20px;" alt="">
                                    </template>
                                    <template #sts="{ row }">
                                        <lay-tag type="primary" v-if="row.sts == '已下架'" size="xs">已下架</lay-tag>
                                        <lay-tag type="normal" v-if="row.sts == '已上架'" size="xs"> 已上架</lay-tag>
                                        <lay-tag type="danger" v-if="row.sts == '待发售'" size="xs">待发售</lay-tag>
                                    </template>
                                    <template #monthTurnover="{ row }">
                                        <p style="color: #d81e06;">
                                            {{ row.monthTurnover }}
                                        </p>
                                        <img src="../../assets/rise.png" style="width: 20px;" alt="">
                                    </template>
                                    <template v-slot:operation="{ row }">
                                        <lay-button type="primary" size="xs" @click="addData('编辑', row)">编辑</lay-button>
                                        <lay-button type="danger" size="xs" @click="deleteData(row)">删除</lay-button>
                                    </template>
                                </lay-table>
                            </lay-tab-item>
                        </lay-tab>
                    </div>
                </lay-tab-item> -->
            </lay-tab>
        </div>

        <lay-layer v-model="updataVisible" :area="['700px', '600px']" shade :shadeOpacity="0.3" :title="updataTitle">
            <div class="a">
                <lay-form :model="addDataForm" size="sm">
                    <lay-form-item label="商品名称">
                        <lay-input v-model="addDataForm.productName" placeholder="请输入商品名称"></lay-input>
                    </lay-form-item>
                    <lay-form-item label="商品规格">
                        <lay-input v-model="addDataForm.otherProductInfo" placeholder="请输入商品规格"></lay-input>
                    </lay-form-item>
                    <lay-form-item label="商品图片">
                        <UploadFile @DeleteImage="DeleteImage" @ImageFile="getImageFile"
                            :imageUrl="addDataForm.productImage">
                        </UploadFile>
                    </lay-form-item>
                    <lay-form-item label="商品价格">
                        <div class="div" style="display: flex;justify-content: space-between;">
                            <div class="div" style="display: flex;align-items: center;">
                                <p style="font-size: 12px;width: 100px;"> 价格：</p>
                                <lay-input v-model="addDataForm.productPrice" placeholder="请输入商品价格" size="xs"
                                    type="number"></lay-input>
                            </div>
                            <div class="div" style="display: flex;align-items: center;">
                                <p style="font-size: 12px;width: 100px;"> 原价：</p>
                                <lay-input v-model="addDataForm.priceOriginal" placeholder="请输入商品价原价" size="xs"
                                    type="number"></lay-input>
                            </div>
                        </div>
                    </lay-form-item>
                    <lay-form-item label="商品运费">
                        <lay-input v-model="addDataForm.express" placeholder="请输入商品运费" type="number"></lay-input>
                    </lay-form-item>
                    <lay-form-item label="商品库存">
                        <lay-input-number v-model="addDataForm.stockQuantity" :step="1"></lay-input-number>
                    </lay-form-item>
                    <lay-form-item label="商品状态">
                        <lay-radio-group v-model="addDataForm.productSts">
                            <lay-radio value="已上架">已上架</lay-radio>
                            <lay-radio value="已下架">已下架</lay-radio>
                            <lay-radio value="待发售">待发售</lay-radio>
                        </lay-radio-group>
                    </lay-form-item>
                    <lay-form-item label="商品介绍">
                        <lay-textarea placeholder="请输入描述" v-model="addDataForm.productDescription">
                        </lay-textarea>
                    </lay-form-item>
                </lay-form>
            </div>
            <template #footer>
                <div class="right a" style="float: right;">
                    <lay-button>重置</lay-button>
                    <lay-button type="primary" @click="submitData">确定</lay-button>
                </div>
            </template>
        </lay-layer>

        <lay-layer v-model="addTabVisible" :area="['700px', '300px']" shade :shadeOpacity="0.3" title="添加分类">
            <div class="a">
                <lay-form :model="addTabForm" size="sm">
                    <lay-form-item label="分类名称">
                        <lay-input v-model="addTabForm.name" placeholder="请输入分类名称"></lay-input>
                    </lay-form-item>
                </lay-form>
            </div>
            <template #footer>
                <div class="right a" style="float: right;">
                    <lay-button>重置</lay-button>
                    <lay-button type="primary" @click="submitType">确定</lay-button>
                </div>
            </template>
        </lay-layer>
    </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { layer } from "@layui/layui-vue";
import UploadFile from '../../components/uploadFile.vue'
import {
    getProducts,
    addProducts,
    deleteProducts,
    updateProducts
} from "../../api/path/products.js"

import {
    uploadFile
} from "../../api/path/uploadFile.js"
const imageUrl = ref('')
const current = ref('1');
const currentType = ref(1);
const goodsLoading = ref(false)
const loadingTab = ref(false)
const updataVisible = ref(false)
const addTabVisible = ref(false)
const updataTitle = ref('')
const goodsSts = ref(1)
const queryValue = ref('')
const page = reactive({ current: 1, limit: 10, total: 100 });
const typeTabList = ref(
    [
        { id: 1, name: '车' },
        { id: 2, name: '上衣' },
        { id: 3, name: '裤子' },
        { id: 4, name: '配饰' },
        { id: 5, name: '包包' },
        { id: 6, name: '内衣' },
        { id: 7, name: '美妆' },
        { id: 8, name: '家居' },
        { id: 9, name: '食品' },
        { id: 10, name: '电器' },
    ]
)
const addDataForm = reactive({
    productID: '',
    productName: '',
    productImage: '',
    productPrice: '',
    priceOriginal: '',
    express: '',
    stockQuantity: '',
    sales: 0,
    productSts: '',
    productDescription: '',
    otherProductInfo: ""
})
const addTabForm = reactive({
    id: '',
    name: ''
})
const columns = ref([
    {
        title: '商品编号',
        key: 'productID',
        width: 80,
    },
    {
        title: '商品名称',
        key: 'productName',
        width: 200,
    },
    {
        title: '商品图片',
        key: 'productImage',
        ellipsisTooltipTheme: true,
        customSlot: "image",
        width: 80,

    },
    {
        title: '商品介绍',
        key: 'productDescription',
        ellipsisTooltip: true,
        width: 200,
    },
    {
        title: '商品状态',
        key: 'productSts',
        customSlot: 'sts',
        width: 120,
    },
    {
        title: '商品价格',
        key: 'productPrice',
        sort: "desc",
        width: 120,
    },
    {
        title: '商品销量',
        key: 'sales',
        sort: "desc",
        width: 120,
    },
    {
        title: '商品库存',
        key: 'stockQuantity',
        sort: "desc",
        width: 120,
    },

    {
        title: '操作',
        key: 'operation',
        customSlot: "operation",
        fixed: 'right',
        ignoreExport: true,
        width: 120,
    },
])
const dataSource = ref([

])

const columnsTab = ref([
    {
        title: '商品编号',
        key: 'id',
        width: 80,
    },
    {
        title: '商品名称',
        key: 'name',
        width: 200,
    },
    {
        title: '商品图片',
        key: 'image',
        ellipsisTooltipTheme: true,
        customSlot: "image",
        width: 80,

    },
    {
        title: '商品介绍',
        key: 'lat',
        ellipsisTooltip: true,
        width: 200,
    },
    {
        title: '商品状态',
        key: 'sts',
        customSlot: 'sts',
        width: 120,
    },
    {
        title: '商品价格',
        key: 'price',
        sort: "desc",
        width: 120,
    },
    {
        title: '商品销量',
        key: 'sales',
        sort: "desc",
        width: 120,
    },
    {
        title: '商品月销量',
        key: 'monthTurnover',
        customSlot: "monthTurnover",
        sort: "desc",
        width: 120,
    },
    {
        title: '商品退货量',
        key: 'goodsReturn',
        sort: "desc",
        width: 120,
        customSlot: "goodsReturn",
    },
    {
        title: '商品库存',
        key: 'stock',
        sort: "desc",
        width: 120,
    },

    {
        title: '操作',
        key: 'operation',
        customSlot: "operation",
        fixed: 'right',
        ignoreExport: true,
        width: 120,
    },
])
const dataSourceTab = ref([])
const pageTab = reactive({ current: 1, limit: 10, total: 100 });

onMounted(() => {
    goodsLoading.value = true
    loadingTab.value = true
    getProductsList()
})

const getProductsList = () => {
    goodsLoading.value = true

    getProducts({ name: queryValue.value }).then(res => {
        setTimeout(() => {
            goodsLoading.value = false
            dataSource.value = res.data
        }, 800)
    }).catch((res => {
        goodsLoading.value = false
    }))
}

const addTab = (val) => {
    addTabVisible.value = true
}

const addData = (title, val) => {
    updataVisible.value = true
    if (title == '添加') {
        updataTitle.value = '添加商品'
        addDataForm.productName = ''
        addDataForm.productID = ''
        addDataForm.productImage = ''
        addDataForm.productPrice = ''
        addDataForm.priceOriginal = ''
        addDataForm.stockQuantity = ''
        addDataForm.express = ''
        addDataForm.sales = ''
        addDataForm.productSts = ''
        addDataForm.productDescription = ''
        imageUrl.value = ''
        // addDataForm.productName = 'xiao mi Su7 Pro Max 创始版',
        //     addDataForm.productPrice = 299000,
        //     addDataForm.priceOriginal = 399000,
        //     addDataForm.stockQuantity = 100,
        //     addDataForm.express = 12,
        //     addDataForm.sales = 0,
        //     addDataForm.productSts = '已上架',
        //     addDataForm.productDescription = '小米汽车推出了全新的SU7电动轿车，这款车型不仅具备出色的性能表现，更将智能科技融入到驾驶体验之中，为消费者带来更加便捷、舒适的出行方式。'
    } else {
        updataTitle.value = '编辑商品'
        addDataForm.productName = val.productName
        addDataForm.productID = val.productID
        addDataForm.productImage = val.productImage
        addDataForm.productPrice = val.productPrice
        addDataForm.priceOriginal = val.priceOriginal
        addDataForm.stockQuantity = val.stockQuantity
        addDataForm.express = val.express
        addDataForm.sales = val.sales
        addDataForm.productSts = val.productSts
        addDataForm.productDescription = val.productDescription
        addDataForm.otherProductInfo = val.otherProductInfo
        imageUrl.value = val.productImage
    }
}


// 子组件删除图片的操作
const DeleteImage = () => {
    addDataForm.productImage = ''
}

const getImageFile = (val) => {
    imageUrl.value = val
    // 获取文件流信息
}


const deleteData = (val) => {
    layer.confirm("确定要删除该商品吗？",
        {
            btn: [
                {
                    text: '确定', callback: (id) => {
                        // layer.close(id);
                        deleteProducts({ id: val.productID }).then(res => {
                            if (res.code == 1) {
                                layer.msg("删除成功");
                                getProductsList()
                            } else {
                                layer.msg("删除失败");
                            }
                        })
                    }
                },
                {
                    text: '取消', callback: (id) => {
                        layer.close(id);
                    }
                }
            ]
        }
    );
}

const submitType = () => {
    addTabVisible.value = false
    typeTabList.value.push({
        id: typeTabList.value[typeTabList.value.length - 1].id + 1,
        name: addTabForm.name,
    })
}



// 搜索商品
const QueryChangeGoods = () => {
    getProductsList()
}
// 上传图片
const uploadFileImage = (callback) => {
    uploadFile(imageUrl.value).then(res => {
        if (res.code == 1) {
            addDataForm.productImage = res.data
            callback()
        } else {
            layer.msg("上传失败");
        }
    })
}
// 添加商品
const submitData = () => {
    layer.load(2, { time: 5000 })
    if (addDataForm.productName == ''
        || imageUrl.value == ''
        || addDataForm.productPrice == ''
        || addDataForm.priceOriginal == ''
        || addDataForm.stockQuantity == ''
        || addDataForm.productSts == '') {
        layer.msg("请填写完整信息");
        setTimeout(() => {
            layer.closeAll()

        }, 1000)
    } else {
        if (updataTitle.value == '添加商品') {
            uploadFileImage(() => {
                layer.closeAll()
                addProducts(addDataForm).then(res => {
                    if (res.code == 1) {
                        layer.msg("添加成功");
                        setTimeout(() => {
                            updataVisible.value = false
                            getProductsList()
                        }, 1000)
                    } else {
                        layer.msg("添加失败");
                    }
                })
            })
        } else if (updataTitle.value == '编辑商品') {
            // 判断当前的图片是否更换过
            // addDataForm.productImage 是否包含 https
            if (addDataForm.productImage.includes('https')) {
                // 没有替换
                updateProducts(addDataForm).then(res => {
                    if (res.code == 1) {
                        layer.msg("编辑成功");
                        setTimeout(() => {
                            updataVisible.value = false
                            getProductsList()
                        }, 1000)
                    } else {
                        layer.msg("编辑失败");
                    }
                })
            } else {
                // 有替换
                uploadFileImage(() => {
                    updateProducts(addDataForm).then(res => {
                        if (res.code == 1) {
                            layer.msg("编辑成功");
                            setTimeout(() => {
                                updataVisible.value = false
                                getProductsList()
                            }, 1000)
                        } else {
                            layer.msg("编辑失败");
                        }
                    })
                })
            }
        }
    }
}
</script>
<style scoped>
.div {
    margin-right: 20px;
}
</style>